package com.itheima.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
    检查登录
 */
@WebFilter({"/index.html","/stuList.html","/manager.html"})
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将请求和响应转换为Http请求和响应
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        //获取会话域中的用户名
        Object username = req.getSession().getAttribute("username");
        //System.out.println(username);
        //判断用户名是否存在
        if (username == null || username.equals("")) {
            //不存在就重定向到登陆页面
            resp.sendRedirect(req.getContextPath() + "/login.html");
            return;
        }
        //放行
        filterChain.doFilter(req, resp);

    }

    @Override
    public void destroy() {

    }
}
